#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time    : 2021/8/6 上午10:00
# @Author  : Samge

from __future__ import print_function
import logging
import grpc

from rpc_package.helloWord_pb2 import HelloRequest
from rpc_package.helloWord_pb2_grpc import HelloWorldServiceStub


def get_client():
    """
    获取rpc客户端对象
    :return:
    """
    # 使用with语法保证channel自动close
    channel = grpc.insecure_channel('localhost:50000')
    # 客户端通过stub来实现rpc通信
    stub = HelloWorldServiceStub(channel)
    return stub, channel
    # # 使用with语法保证channel自动close
    # with grpc.insecure_channel('localhost:50000') as channel:
    #     # 客户端通过stub来实现rpc通信
    #     stub = HelloWorldServiceStub(channel)
    # return stub


def run():
    stub, channel = get_client()

    response = stub.SayHello(HelloRequest(name='eric'))
    print(f"hello client received: {response}")

    response = stub.test(HelloRequest(name='eric'))
    print("hello client received: " + response.message)

    channel.close()


if __name__ == "__main__":
    logging.basicConfig()
    run()
